package com.webserver.http;

import static com.webserver.http.HttpContext.CR;
import static com.webserver.http.HttpContext.LF;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象
 * 该类的每一个实例用于表示HTTP协议规则的客户端发送过来的一个请求
 * 每个请求由三部分构成:
 * 请求行 消息头 消息正文
 */
public class HttpServletRequest {
    //请求行相关信息
    String method;//请求方式
    String uri;//抽象路径
    String protocol;//协议版本

    //保存所有消息头,key:消息头的名字 value:消息头对应的值
    Map<String, String> headers = new HashMap<>();

    private Socket socket;

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        // 1 解析请求
        //1.1 解析请求行
        parseRequestLine();
        //1.2 解析消息头
        parseHeaders();
        //1.3 解析消息正文
        parseContent();
    }


    //解析请求行
    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);
        String[] ss = line.split("\\s");

        method = ss[0];
        uri = ss[1];
        protocol = ss[2];

        System.out.println("method:" + method);
        System.out.println("uri:" + uri);
        System.out.println("protocol:" + protocol);
    }

    //解析消息头
    private void parseHeaders() throws IOException {
        while (true) {
            String line = readLine();
            if (line.isEmpty()) {
                break;
            }
            System.out.println("消息头: " + line);
            String[] s = line.split(":\\s");
            headers.put(s[0], s[1]);
        }
    }

    //解析消息正文
    private void parseContent() {

    }


    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char c = 'a', p = 'a';
        while ((d = in.read()) != -1) {
            c = (char) d;
            if (p == CR && c == LF) {
                break;
            }
            builder.append(c);
            p = c;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }

}
